# @Time : 2021/6/1 17:32
# @Author : Fioman 
# @Phone : 13149920693

"""
模拟一个服务器,用来本地测试.
"""
import random
import socket
from hd_socket.xml_parser import *
from settings import EAP_SEND_MOCK_PATH

BUFFER_SIZE = 16384  # 设置读物的一次BUFFER_SIZE的大小.16K
EAP_IP = "127.0.0.1"
PORT = 5000
ADDR = (EAP_IP, PORT)


def modify_buffer_size(hdSock):
    """
    设置一次读取的buffer大小,提高性能
    :param hdSock: 使用的socket套接字
    :return:
    """
    # 获取当前套接字关联的选项,socket.SOL_SOCKET,正在使用的socket,socket.SOCK_STREAM发送缓存区的大小
    hdSock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
    hdSock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)

    # 设置TCP套接字关联的选项
    # socket.TCP_NODELAY TCP层套接口选项
    # socket.TCP_NODELAY.表示禁用了Nagle,允许小包发送.不用等很多的包折合一起再发送的问题.适用于数据量小的项目.
    hdSock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)

    # 设置发送缓存区套接字关联的选项
    hdSock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, BUFFER_SIZE)
    # 设置接收缓存区套接字关联的选项
    hdSock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BUFFER_SIZE)


def send_recipe_data_to_device(tcpClientSock):
    """
    模拟发送消息到设备
    :param tcpClientSock socket的套接字
    :return:
    """
    data = get_recipe_data()
    if data is not None:
        msgSend = bytes(chr(2), encoding="ascii") + data + bytes(chr(3), encoding="ascii")
        tcpClientSock.sendall(msgSend)


def get_recipe_data():
    msgHeader = "ParamIssue"
    bodyDict = {
        "recipeName": "test",
        "width": str(random.randint(500, 700)),
        "height": str(random.randint(500, 700)),
        "cropperThick": str(random.randint(0, 3)),
        "jointNumber": "2",
        "isBroken": "否"
    }
    retDict = {
        "returncode": "0",
        "returnmessage": ""
    }
    pack_eap_mock_send_msg(msgHeader, bodyDict, retDict)

    with open(EAP_SEND_MOCK_PATH,"rb") as f:
        data = f.read()
    return data


if __name__ == '__main__':
    tcpServerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcpServerSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    modify_buffer_size(tcpServerSock)
    tcpServerSock.bind(ADDR)
    tcpServerSock.listen(5)

    while True:
        print("waiting for connection...")
        tcpClientSock, addr = tcpServerSock.accept()
        print("...connected from: {}".format(addr))

        while True:
            data = tcpClientSock.recv(BUFFER_SIZE)
            if not data:
                print("data is None,内层循环退出,连接退出")
                break
            print("receive Data: {}".format(data))
            send_recipe_data_to_device(tcpClientSock)
        tcpClientSock.close()
